package com.weijin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.hutool.core.util.StrUtil;
import com.weijin.vo.PageVo;
import com.weijin.mapper.UserMapper;
import com.weijin.model.User;
import com.weijin.service.IUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 用户服务业务逻辑代码
 *
 * @Author WeiJin
 * @Version 1.0
 * @Date 2025/3/18 14:10
 */
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public String addUser(User user) {
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户信息不能为空");
        }
        //返回插入到表中的数量
        int insert = userMapper.insert(user);
        if (insert > 0) {
            return user.getId();
        }
        throw new RuntimeException("新增用户失败");
    }

    @Override
    public int deleteOne(String id) {
        int delete = userMapper.deleteById(id);
        //判断是否删除成功
        if (delete > 0) {
            return delete;
        }
        throw new RuntimeException("删除失败！id:" + id);
    }

    @Override
    public User editByUserId(User user) {
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户信息为空，更新失败");
        }
        int update = userMapper.updateById(user);
        if (update > 0) {
            return user;
        }
        throw new RuntimeException("更新用户失败");
    }

    @Override
    public User detail(String id) {
        if (StrUtil.isBlank(id)) {
            throw new RuntimeException("用户id为空，查询失败");
        }
        User user = userMapper.selectById(id);
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户不存在");
        }
        return user;
    }

    @Override
    public PageVo<User> page(String username, int pageNumber, int pageSize) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .like(StrUtil.isNotBlank(username), User::getName, username);
        Page<User> userPage = new Page<>(pageNumber, pageSize);
        Page<User> page = userMapper.selectPage(userPage, wrapper);
        return new PageVo<>(page);
    }

    @Override
    public User login(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>().eq(User::getName, username);
        User user = userMapper.selectList(wrapper).get(0);
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户" + username + "不存在");
        }
        return user;
    }
}
